package com.capinfo.accumulation.service.collection.impl;

import com.capinfo.accumulation.model.collection.Freeze;
import com.capinfo.accumulation.model.collection.Person;
import com.capinfo.accumulation.parameter.collection.FreezeParameter;
import com.capinfo.accumulation.parameter.collection.PersonParameter;
import com.capinfo.accumulation.service.collection.FreezeService;
import com.capinfo.accumulation.service.collection.PersonService;
import com.capinfo.framework.dao.SearchCriteriaBuilder;
import com.capinfo.framework.dao.impl.restriction.RestrictionExpression;
import com.capinfo.framework.service.impl.CommonsDataOperationServiceImpl;
import com.capinfo.framework.util.LogUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by thinkpadwyl on 2017/10/19.
 */
public class FreezeServiceImpl extends CommonsDataOperationServiceImpl<Freeze, FreezeParameter> implements FreezeService {
    private static final Log logger = LogFactory.getLog(Freeze.class);

    @Autowired
    PersonService personService;

    @Override
    public boolean isExist(FreezeParameter parameter){
        return  false;
    }

    @Override
    public boolean freezeAudit(FreezeParameter parameter){
        Freeze freeze = parameter.getEntity();

        Freeze saveFreeze = null;

        try {
            saveFreeze = getGeneralService().getObjectById(Freeze.class,freeze.getId());
            if(saveFreeze != null) {
                saveFreeze.setState(1L);  //冻结状态：1
                getGeneralService().update(saveFreeze);
                //个人冻结状态修改
                if(saveFreeze.getPersonId() != null) {
                    Person person = getGeneralService().getObjectById(Person.class, saveFreeze.getPersonId());
                    if (person != null){
                        person.setIsFreeze(1L);
                        personService.saveOrUpdate(person);
                    }
                }
            }
            return true;
        }catch (Exception e) {
            LogUtils.debugException(logger, e);
        }

        return  false;
    }

    @Override
    public boolean unfreezeAudit(FreezeParameter parameter){
        Freeze freeze = parameter.getEntity();

        Freeze saveFreeze = null;

        try {
            saveFreeze = getGeneralService().getObjectById(Freeze.class,freeze.getId());
            if(saveFreeze != null) {
                saveFreeze.setState(3L);
                getGeneralService().update(saveFreeze);
                //个人解冻状态修改
                if(saveFreeze.getPersonId() != null) {
                     Person person = null;
                     getGeneralService().fetchLazyProperty(person,"id");
                     person = getGeneralService().getObjectById(Person.class, saveFreeze.getPersonId());

                     if (person != null){
                        SearchCriteriaBuilder<Freeze> searchCriteriaBuilder = new SearchCriteriaBuilder<Freeze>(Freeze.class);
                        searchCriteriaBuilder.addQueryCondition("personId",RestrictionExpression.EQUALS_OP,saveFreeze.getPersonId());
                        List<Freeze> freezes = this.getGeneralService().getObjects(searchCriteriaBuilder.build());
                        if(freezes != null && freezes.size() > 0) {

                            if(freezes.size() == 1) {
                                person.setIsFreeze(0L);
                                personService.saveOrUpdate(person);
                            }else{
                                int i_js = 0;
                                for (Freeze curFreeze: freezes) {
                                    if(saveFreeze.getId() == curFreeze.getId()){
                                        i_js++;
                                        continue;
                                    }
                                    if(curFreeze.getState() == 3L)
                                        i_js++;

                                }
                                if(i_js == freezes.size()){
                                    person.setIsFreeze(0L);
                                    personService.saveOrUpdate(person);
                                }
                            }
                        }
                    }
                }
            }
            return true;
        }catch (Exception e) {
            LogUtils.debugException(logger, e);
        }

        return  false;
    }

    @Override
    public void unfreezeJob(){
        SearchCriteriaBuilder<Freeze> searchCriteriaBuilder = new SearchCriteriaBuilder<Freeze>(Freeze.class);
        searchCriteriaBuilder.addQueryCondition("state",RestrictionExpression.EQUALS_OP,1L);
        String strEndDate = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        searchCriteriaBuilder.addQueryCondition("endTime",RestrictionExpression.LESS_EQUALS_OP,strEndDate);
        List<Freeze> freezes = this.getGeneralService().getObjects(searchCriteriaBuilder.build());
        FreezeParameter freezeParameter = new FreezeParameter();
        if(freezes != null && freezes.size() > 0) {
            for (Freeze curFreeze: freezes) {
                if(DateUtils.isSameDay(new Date(),curFreeze.getEndTime())){
                    freezeParameter.setEntity(curFreeze);
                    this.unfreezeAudit(freezeParameter);
                }
            }
        }
    }

    @Override
    public boolean delay(FreezeParameter parameter){
        Freeze freeze = parameter.getEntity();
        Long freezePeroid =  freeze.getFreezePeriod();
        Date endTime = freeze.getEndTime();
        Freeze saveFreeze = null;

        try {
            saveFreeze = getGeneralService().getObjectById(Freeze.class,freeze.getId());
            if(saveFreeze != null) {
                saveFreeze.setFreezePeriod(freezePeroid);
                saveFreeze.setEndTime(endTime);
                getGeneralService().update(saveFreeze);
            }
            return true;
        }catch (Exception e) {
            LogUtils.debugException(logger, e);
        }

        return  false;
    }
    @Override
    public boolean unfreeze(FreezeParameter parameter) {
        Freeze freeze = parameter.getEntity();

        Freeze saveFreeze = null;

        try {
            saveFreeze = getGeneralService().getObjectById(Freeze.class,freeze.getId());
            if(saveFreeze != null) {
                saveFreeze.setUnfreezeReasonId(freeze.getUnfreezeReasonId());
                saveFreeze.setState(2L);
                if(StringUtils.isBlank(freeze.getRemark()))
                    saveFreeze.setRemark(freeze.getRemark());
                getGeneralService().update(saveFreeze);
            }
            return true;
        }catch (Exception e) {
            LogUtils.debugException(logger, e);
        }

        return  false;
    }

    @Override
    public SearchCriteriaBuilder<Freeze> getSearchCriteriaBuilder(FreezeParameter parameter){
        SearchCriteriaBuilder<Freeze> searchCriteriaBuilder = super.getSearchCriteriaBuilder(parameter);

        if(!StringUtils.isBlank(parameter.getFreezeFlag()) ){
            if(parameter.getFreezeFlag().equals("1") )
                searchCriteriaBuilder.addQueryCondition("state", RestrictionExpression.EQUALS_OP, 0L);
            if(parameter.getFreezeFlag().equals("2") )
                searchCriteriaBuilder.addQueryCondition("state", RestrictionExpression.EQUALS_OP, 1L);
            if(parameter.getFreezeFlag().equals("3") ) {
                searchCriteriaBuilder.addQueryCondition("state", RestrictionExpression.GREATER_EQUALS_OP, 1L);
                searchCriteriaBuilder.addQueryCondition("state", RestrictionExpression.LESS_THAN_OP, 3L);
            }
        }
        if(parameter.getEntity() != null) {
            String strStartDate = (new SimpleDateFormat("yyyy-MM-dd")).format(parameter.getEntity().getStartTime());
            String strEndDate = (new SimpleDateFormat("yyyy-MM-dd")).format(parameter.getEntity().getEndTime());
            searchCriteriaBuilder.addQueryCondition("startTime", RestrictionExpression.GREATER_EQUALS_OP, strStartDate);
            searchCriteriaBuilder.addQueryCondition("endTime", RestrictionExpression.LESS_EQUALS_OP, strEndDate);
        }
        //searchCriteriaBuilder.addQueryCondition("regionId", RestrictionExpression.EQUALS_OP, parameter.getEntity().getRegionId());

        if(parameter.getEntity().getPerson() != null) {
            searchCriteriaBuilder.addQueryCondition("person.personalAccount", RestrictionExpression.EQUALS_OP, parameter.getEntity().getPerson().getPersonalAccount());
            searchCriteriaBuilder.addQueryCondition("person.idCardNumber", RestrictionExpression.EQUALS_OP, parameter.getEntity().getPerson().getIdCardNumber());
            searchCriteriaBuilder.addQueryCondition("person.name", RestrictionExpression.LIKE_OP, parameter.getEntity().getPerson().getName());

            if(parameter.getEntity().getPerson().getCompany() != null){
                searchCriteriaBuilder.addQueryCondition("person.company.gbCompanyAccount", RestrictionExpression.EQUALS_OP, parameter.getEntity().getPerson().getCompany().getGbCompanyAccount());
                searchCriteriaBuilder.addQueryCondition("person.company.gbCompanyName", RestrictionExpression.LIKE_OP, parameter.getEntity().getPerson().getCompany().getGbCompanyName());
            }
        }
        return searchCriteriaBuilder;
    }
}
